/**
 *
 * @author ace
 * @create 2017/7/20
 */
class MsgManager extends NotifyEvent {

    read(cmd: number, data: any) {
        if (!cmd) return;

        switch (cmd) {
            case 1://登录
                console.log('登录游戏！');

                game.player.update(data);

                if (GameConfig.wx_code) GameStorage.setData(GameStorage.wx_code, GameConfig.wx_code);
                if (game.player.uid) GameStorage.setData(GameStorage.uid, game.player.uid);
                if (game.player.code) GameStorage.setData(GameStorage.code, game.player.code);

                if (data.hasOwnProperty('w_auth')) {
                    let auth: any = data.w_auth;
                    Weixin.config(
                        GameConfig.appid,
                        auth.timestamp,
                        auth.noncestr,
                        auth.signature,
                        GameConst.Wx_Apilist
                    );
                }

                //回放分享的情况
                if (Replayer.shareIF.isSharePlayback) {
                    Replayer.requestPlayback();
                } else {
                    gameManager.open("MainScene");
                }
                break;
            case 24://同步房卡
                console.log("同步房卡！");

                game.player.update(data);

                let main: MainScene = gameManager.find('MainScene');
                if (main) main.update();
                break;
            case 35://同步用户信息
                console.log("同步同步用户信息！");

                game.player.update(data);

                gameManager.i.dispatchEvent(GameEventType.UPDATE_PLAYER_INFO);
                break;
            case 18://心跳
                console.log("心跳！");
                gameManager.socketManager.send(18);
                break;
            case 26://同步版本号
                console.log("同步版本号！");
                break;


            //----------------------------房间
            case 2://创建房间
                console.log('创建房间！-ID：', data.roomid);

                game.roomid = data.roomid;
                game.roomCreateTime = data.create_time;
                game.roomState = RoomState.NORMAL;

                game.player.cur = data.cur;

                game.poswx && gameManager.socketManager.send(501, { pos: game.poswx });

                gameManager.close("CreatePanel");
                break;
            case 3://加入房间
                console.log('加入房间！');

                gameManager.close('JoininPanel');
                game.roomState = RoomState.NORMAL;
                game.poswx && gameManager.socketManager.send(501, { pos: game.poswx });

                game.isDaikai = data.hasOwnProperty('dai_kai') && data.dai_kai == 1;
                break;
            case 5://断线重连
                console.log("断线重连！");

                game.poswx && gameManager.socketManager.send(501, { pos: game.poswx });

                game.isDaikai = data.hasOwnProperty('dai_kai') && data.dai_kai == 1;

                GSController.i.exit();
                GSDataProxy.i.S2C_RebackData(data);
                break;
            case 6://房间解散
                console.log("房间解散！");

                GSController.i.exit();
                game.roomClean();

                game.askPanel.showMsg(null, "房间解散了，请进入其他房间！", null, null, true);
                break;
            case 14://解散房间
                console.log("解散房间！");

                game.dissolution = new DissolutionVo();
                game.dissolution.vote = data.vote;
                game.dissolution.timestamp = data.timestamp;

                if (data.close && data.tips) {
                    EffectTextUtils.showTips("房间解散成功", 5);
                }

                let dissolutionPanel: DissolutionPanel = gameManager.open('DissolutionPanel', false);
                if (dissolutionPanel) {
                    dissolutionPanel.refresh();

                    if (data.close && !data.tips) {
                        egret.setTimeout(function () {
                            dissolutionPanel.hide();
                            GSUpdate.i.stop();
                        }, dissolutionPanel, 1000);
                    }
                }
                break;
            case 12://离开房间
                console.log("离开房间！");

                GSController.i.exit();
                game.roomClean();
                break;
            case 22://踢出房间
                console.log("踢出房间！");
                break;
            case 23://被踢出房间
                console.log("被踢出房间！");

                EffectTextUtils.showTips("你被房主踢出了房间！");
                GSController.i.exit();
                break;
            case 25://房间广播
                console.log("房间广播！");

                this.broadcast(data);
                break;
            case 8://同步房间人员信息
                console.log("同步房间人员信息！");

                this.playerInfo(data);
                break;


            //----------------------------游戏
            case 10://开始游戏
                console.log("开始游戏！");
                break;
            case 17://继续游戏
                console.log("继续游戏！");

                GSDataProxy.i.S2C_ContinueGame(data);
                break;
            case 11://系统通知
                console.log("系统通知！");

                this.gameSystem(data);
                break;
            case 9://游戏通知
                console.log("游戏通知！");

                this.gameInfo(data);
                break;
            case 4://收到出牌
                console.log("收到出牌！");

                GSDataProxy.i.S2C_PoolPai(data);
                break;
            case 15://中断处理
                break;
            case 16://牌局结算
                console.log("牌局结算！");

                data.person.sort(function (a: any, b: any) {
                    return PublicVal.i.getDir(a.pos) < PublicVal.i.getDir(b.pos) ? -1 : 1;
                });

                GSDataProxy.i.S2C_FinalResult(data);

                gameManager.i.dispatchEvent(EffectEvent.CardThrow);
                gameManager.i.dispatchEvent(EffectEvent.CardThrowTips);
                break;
            case 13://游戏结束
                console.log("游戏结束！");

                GSController.i.jiesuanData = data;

                let diss: DissolutionPanel = gameManager.find('DissolutionPanel');
                if (diss && gameManager.layerManager.panelLayer.contains(diss)) {
                    GSController.i.closeResultView();
                    GSController.i.closeGSView();
                    GSController.i.showTitleView(GSController.i.jiesuanData);

                    diss.hide();

                    game.dissolution = null;
                }
                break;

            //----------------------------战绩
            case 19://战绩列表
                console.log("战绩列表！");

                data.return_data.sort(function (a: any, b: any) {
                    return a.time > b.time ? -1 : 1;
                });

                if (!data.return_data || data.return_data.length <= 0) {
                    EffectTextUtils.showTips(`暂无战绩，快去邀请小伙伴一起玩吧！`, 5);
                }
                else {
                    // gameManager.open('RecordPanel');
                    let panel: RecordPanel = gameManager.find('RecordPanel');
                    if (panel && (!panel.visible || !panel.parent == null)) {
                        panel.show();
                    }
                }

                gameManager.i.dispatchEvent(GameEventType.UPDATE_RECORD_LIST, data);
                break;
            case 20://战绩详情
                console.log("战绩详情！");

                data.sort(function (a: any[], b: any[]) {
                    return a[0] < b[0] ? -1 : 1;
                });

                gameManager.i.dispatchEvent(GameEventType.UPDATE_RECORD_DETAILS_LIST, data);
                gameManager.i.dispatchEvent(GameEventType.UPDATE_DAIKAI_DETAILS_LIST, data);
                break;

            //----------------------------回放
            case 21://回放数据
                console.log("回放数据！");

                gameManager.close('RecordPanel');
                gameManager.close('DaikaiPanel');
                gameManager.close("CircleMainPanelAI");
                Replayer.i.parseData(data);
                break;
            case 71://分享回放数据
                Replayer.responsePlayback(data);
                break;


            //----------------------------身份认证
            case 27://身份认证
                console.log("身份认证！");

                game.player.update(data);

                EffectTextUtils.showTips("身份信息认证成功！");

                gameManager.close('RealnamePanel');

                gameManager.i.dispatchEvent(GameEventType.REALNAME_CONFIRM);
                break;


            //----------------------------评价
            case 28://评价记录
                console.log("评价记录！");

                if (data.length <= 0) {
                    EffectTextUtils.showTips(`暂无可以评价的牌局，快去邀请小伙伴一起玩吧！`, 5);
                    return;
                }
                else if (game.isShowAsscess) {
                    gameManager.open('AssessPanel', false);
                }

                gameManager.i.dispatchEvent(GameEventType.UPDATE_ASSESS_LIST, data);
                break;
            case 29://修改评价
                console.log("修改评价！");

                gameManager.socketManager.send(28);
                break;


            //----------------------------代开房
            case 30://创建
                gameManager.open('DaikaiPanel');
                break;
            case 31://列表

                data.sort(function (a: any, b: any) {
                    let ai: number = a.status == 'wait' ? 100 : 0;
                    let bi: number = b.status == 'wait' ? 100 : 0;

                    ai += a.create_time > b.create_time ? 1 : 0;
                    bi += b.create_time > a.create_time ? 1 : 0;

                    return ai > bi ? -1 : 1;
                    // return a.create_time > b.create_time ? -1 : 1;
                });

                gameManager.i.dispatchEvent(GameEventType.UPDATE_DAIKAI_LIST, data);
                break;
            case 32://历史

                if (data.hasOwnProperty('return_data')) {
                    data.return_data.sort(function (a: any, b: any) {
                        return a.time > b.time ? -1 : 1;
                    });
                }
                else {
                    data.sort(function (a: any, b: any) {
                        return a.time > b.time ? -1 : 1;
                    });
                }

                gameManager.i.dispatchEvent(GameEventType.UPDATE_DAIKAI_RECORD_LIST, data);
                break;
            case 33://踢人
                gameManager.socketManager.send(31, { type: GameConfig.gameType });
                break;
            case 34://解散
                gameManager.socketManager.send(31, { type: GameConfig.gameType });
                break;
            /**中间状态处理 */
            case 36://收到问询
                //回复
                gameManager.socketManager.send(37, {});
                break;
            case 38://有人网络收到反馈
                GSDataProxy.i.S2C_Ask(data);
                console.log("收到反馈 网络状况不稳定");
                break;
            case 39://网络不稳状态 清除
                GSDataProxy.i.S2C_ClearAsk(data);
                console.log("清理状态 恢复网络");
                break;
            case 40://胡牌提示
                console.log("收到胡牌提示 ");
                GSDataProxy.i.S2C_tingTishi(data);
                break;



            //----------------------------手机认证
            case 407://手机号认证
                EffectTextUtils.showTips("认证成功");

                game.player.gid = data;
                game.player.isVip = true;

                gameManager.i.dispatchEvent(GameEventType.TELPHONE_CONFIRM);
                break;
            case 408://手机号查询
                game.player.phone = data;
                gameManager.i.dispatchEvent(GameEventType.TELPHONE, data);
                break;
            case 409://记录地理位置
                break;

            //----------------------------测距
            case 501://位置通知
                break;
            case 502://测距数据
                gameManager.i.dispatchEvent(GameEventType.UPDATE_DISTANCE_INFO, data);
                break;

            //----------------------------老友圈
            case 2012://游戏内点击老友圈
                gameManager.viewManager.open("CircleJoinPanel", false);

                gameManager.i.dispatchEvent(GameEventType.Circle_2012, data);
                break;
            case 2013://游戏内点击老友圈进入后面板后的加入圈子查询圈子的信息

                var dialog = gameManager.viewManager.find("CircleJoinPassPanel");
                if (dialog) dialog.hide();
                CircleJoinPanel.state = "result";
                gameManager.viewManager.open("CircleJoinPanel", false);
                gameManager.i.dispatchEvent(GameEventType.Circle_2013, data);

                break;
            case 2014://游戏内点击老友圈进入后面板后的加入圈子查询圈子的信息点击申请加入
                break;
            case 2015://游戏内点击老友圈进入后面板后的进入圈子获取牌局

                //本地记录进入圈子的参数信息，下次直接登陆使用
                if (Circle.tosave_2015) {

                    Circle.tosave_2015 = false;

                    Circle.save_args_2015();

                }

                Circle.circle_data.zhu_name = data.zhu_name;
                Circle.circleNokai = data.nokai;
                var panel = gameManager.viewManager.find("CircleJoinPanel");
                if (panel && panel.parent !== null) panel.hide();

                panel = gameManager.find("CircleMainPanelAI");
                if (panel && panel.parent == null) {
                    gameManager.viewManager.open("CircleMainPanelAI", true, 0);
                }
                gameManager.i.dispatchEvent(GameEventType.Circle_2015, data);

                break;
            case 2016://游戏内点击老友圈进入后面板后的进入圈子获取战绩

                gameManager.i.dispatchEvent(GameEventType.Circle_2016, data);

                break;
            case 2017://游戏内点击老友圈进入后面板后的加入游戏(加入按钮点击)

                if (!data) return;

                Circle.circle_data.zhu_name = data.zhu_name;

                game.roomState = RoomState.CIRCLE;
                game.roomid = data.roomid ? data.roomid : game.roomid;
                //关闭老友圈主面板
                var dialog = gameManager.find("CircleMainPanelAI");

                if (dialog) dialog.hide();

                break;
            //case 2018://游戏内点击老友圈踢人 用代开的踢人
            case 2019://游戏内点击老友圈进入后面板后离开圈子
                break;
            case 2020://游戏内点击老友圈进入后面板后修改规则

                var panel = gameManager.find("CircleCreatePanel");
                if (panel) panel.hide();
                Circle.circle_send(2015, Circle.args_2015);
                break;
            case 2023://服务器主动下推当前房间信息

                if (Circle.args_2015 && data.nokai.circle_id == Circle.args_2015.id) {
                    if (data.nokai) {
                        Circle.circleNokai = data.nokai;
                    }
                    gameManager.i.dispatchEvent(GameEventType.Circle_2023, data);
                    var panel = gameManager.find("CircleCreatePanel");
                    if (panel && panel.parent !== null) {
                        panel.hide();
                        Circle.circle_send(2015, Circle.args_2015);
                    }
                }
                break;
            //----------------------------房卡记录
            case 601://房卡记录
                console.log("房卡记录");

                // if (data.hasOwnProperty('return_data')) {
                //     data.return_data.sort(function (a: any, b: any) {
                //         return a.time > b.time ? -1 : 1;
                //     });
                // }
                // else {
                //     data.sort(function (a: any, b: any) {
                //         return a.time > b.time ? -1 : 1;
                //     });
                // }

                gameManager.i.dispatchEvent(GameEventType.UPDATE_BUYCARD_LIST, data);
                break;

        }
    }
    /**错误处理 */
    readCode(cmd: number, code: number, read: any) {
        if (!cmd) return;
        if (code == 0) return;

        const data: any = read.data;
        let msg: string = GameConfig.errorCodes[code];
        EffectTextUtils.showTips(msg ? msg : "错误代码：" + code, 5);

        switch (code) {
            //老友圈被提出房间后再次进入老友圈加入界面
            case 1014:
                Circle.del_args_2015();
                gameManager.socketManager.send(2012, { uid: game.player.uid });
                var panel: BasePanel = gameManager.find("CircleMainPanelAI");
                if (panel) panel.hide();
                break;
            case 1020://老友圈申请成功
            case 1011://老友圈已申请过
                var panel: BasePanel = gameManager.find("CircleJoinPanel");
                if (panel) panel.hide();
                break;
        }
    }
    //广播
    private broadcast(data: any) {

        if (!data.message) return;

        switch (data.message.type) {
            case 1://同步聊天
                gameManager.i.dispatchEvent(GameEventType.UPDATE_CHAT, data.message.chat);
                break;
            case 2://语音聊天
                break;
            case 3://牌局开始判断
                GSDataProxy.i.S2C_RoundReadyAll();
                break;
            case 4://聊天表情
                gameManager.i.dispatchEvent(GameEventType.UPDATE_EXPRESSION, data.message.expression);
                break;
        }
    }

    //人员信息
    private playerInfo(data: any) {
        if (data.hasOwnProperty("rules")) {
            game.roomRules = data.rules;
        }

        if (data.hasOwnProperty("ren")) {
            game.roomSeat = data.ren;
        }

        if (data.hasOwnProperty("create_time")) {
            game.roomCreateTime = data.create_time;
        }

        if (data.hasOwnProperty("round_type")) {
            game.roomRoundType = data.round_type;
        }

        if (data.hasOwnProperty("round")) {
            game.roomRound = data.round;
        }

        if (data.hasOwnProperty("infos")) {
            let infos: any[] = data.infos;
            let player: PlayerVo;

            for (let i = 0; i < infos.length; i++) {
                player = new PlayerVo();

                if (game.roomPlayers[player.uid]) {
                    player = game.roomPlayers[infos[i].uid];
                }
                else {
                    player = new PlayerVo();
                }

                player.update(infos[i]);

                if (player.uid != game.player.uid) {
                    switch (player.status) {
                        case "leave":
                            GameSound.play("sound_other_player_leave");
                            EffectTextUtils.showTips(player.nick + " 离开了房间！", 4);
                            break;
                        case "offline":
                            GameSound.play("sound_other_player_leave");
                            EffectTextUtils.showTips(player.nick + " 离线了！", 4);
                            GSController.i.updateHeadEffect(player.pos, HeadEffType.flash, false);
                            break;
                        case "online":
                            GameSound.play("sound_other_player_enter");
                            EffectTextUtils.showTips(player.nick + (game.roomPlayers[player.uid] ? " 回来了！" : " 加入了游戏！"), 4);
                            break;
                    }
                }

                game.roomPlayers[infos[i].uid] = player;

                if (player.uid == game.player.uid) {
                    game.roomPos = player.pos;
                    PublicVal.i.ownPos = game.roomPos;
                    game.isRoomOwner = game.roomPos == 1;
                    GSDataProxy.i.gData.firstInRoom = true;
                    GameHandy.mappingDir(game.roomPos);
                }
            }

            gameManager.socketManager.send(502);
        }

        GSDataProxy.i.S2C_RoomPlayers();

        GameConfig.initShare(game.isDaikai);
    }

    //游戏系统消息 11
    private gameSystem(data: any) {
        switch (+data.action) {
            case 100://初始手牌
                console.log("初始手牌！");

                GSDataProxy.i.S2C_OwnCardInfo(data);
                break;
            case 200://自己抓牌
                console.log("自己抓牌！");

                GSDataProxy.i.S2C_OwnCatch(data.pai[0], data.dui_num, data.hasOwnProperty("fen"));

                gameManager.i.dispatchEvent(EffectEvent.CardThrow);
                gameManager.i.dispatchEvent(EffectEvent.CardRaise);

                GSController.i.gsView.resetAllChildrenTouch();
                break;
            case 300://换宝
                console.log("换宝！");

                GSDataProxy.i.S2C_Bao(data);
                break;
            case 303://看宝
                console.log("看宝---", data);
                GSDataProxy.i.S2C_LookBao(data);
                break;
            case 301://换三张
                console.log("换三张！");

                game.isChangeThree = true;

                let pais: any = data.pai;
                for (let i: number = 0; i < pais.length; i++) {
                    PublicVal.i.addHandPai(1, pais[i]);
                    PublicVal.i.addHandPai(2, null);
                    PublicVal.i.addHandPai(3, null);
                    PublicVal.i.addHandPai(4, null);
                }

                FashionTools.sortPai(PublicVal.i.getHandPais(1));

                gameManager.i.dispatchEvent(EffectEvent.ChangeThreeComplete, data.huan_type);
                break;
            case 302://订缺
                console.log("订缺！");
                break;
            default://同步自己的功能牌
                console.log("同步自己的功能牌！");

                GSDataProxy.i.S2C_FuncResult(data);

                gameManager.i.dispatchEvent(EffectEvent.CardThrow);
                gameManager.i.dispatchEvent(EffectEvent.CardThrowTips);

                GSController.i.gsView.resetAllChildrenTouch();
                break;
        }
    }

    //游戏信息  9
    private gameInfo(data: any) {
        switch (+data.type) {
            case 1://通知房主开启游戏
                console.log("房主开启游戏！");
                break;
            case 2://到谁抓牌
                console.log("到谁抓牌！");

                let gang_end = data.data.gang_end;
                let dui_num: number = data.data.dui_num;
                let pos: number = +data.data.pos;

                game.status = StateExType.gamestart;
                game.statusComplete = true;

                GSDataProxy.i.S2C_TurnDir(pos, dui_num, gang_end);

                gameManager.i.dispatchEvent(EffectEvent.CardThrow);
                break;
            case 3://功能菜单
                console.log("功能菜单！");

                GSDataProxy.i.S2C_Function(data.data);
                break;
            case 4://功能菜单
                console.log("功能菜单-其他！");

                GSDataProxy.i.S2C_FuncResult(data.data);

                gameManager.i.dispatchEvent(EffectEvent.CardThrow);
                gameManager.i.dispatchEvent(EffectEvent.CardThrowTips);
                break;
            case 5: //删除手牌
                console.log("删除手牌！");

                GSDataProxy.i.S2C_DeletePai(data.data.pos, data.data.pai);
                break;
            case 6://补杠提示
                console.log("补杠提示！");

                gameManager.i.dispatchEvent(EffectEvent.CardThrow, [PublicVal.i.getDir(data.data.pos), data.data.pai]);
                break;
            case 9://换三张
                break;
            case 10://订缺
                break;
            case 11://同步换三张
                break;
            case 12://同步订缺
                break;
        }
    }
}